package com.liu.webstore.controller;

import com.liu.webstore.entity.DiscussPost;
import com.liu.webstore.entity.Page;
import com.liu.webstore.entity.User;
import com.liu.webstore.enums.StatusEnum;
import com.liu.webstore.service.DiscussPostService;
import com.liu.webstore.service.LikeService;
import com.liu.webstore.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.*;

/**
 * @Author LiuYumei
 * @Date 2022/7/11 23:05
 */
@Controller
@RequestMapping("/home")
public class HomeController {
    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    @GetMapping("/index")
    public String getIndexPage(Model model, Page page) {
        // 方法调用前，springMVC会自动实例化Model和Page，并将Page注入Model中。在thymeleaf可以直接访问Page对象数据
        page.setRows(discussPostService.selectDiscussPostRows(0));
        page.setPath("/home/index");
        List<DiscussPost> list = discussPostService.selectDiscussPosts(0, page.getOffert(), page.getLimit());
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        if (Objects.nonNull(list)) {
            for (DiscussPost discussPost : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("post", discussPost);
                User user = userService.getUserById(discussPost.getUserId());
                map.put("user", user);

                // 点赞数
                Long likeCount = likeService.findEntityLikeCount(StatusEnum.ENTITY_TYPE_POST.getStatus(), discussPost.getId());
                map.put("likeCount", likeCount);
                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPosts", discussPosts);
        return "index";
    }

    @GetMapping("/error")
    public String getErrorPage() {
        return "/error/500";
    }

    @GetMapping("/denied")
    public String getDeniedPage() {
        return "/error/404";
    }
}
